﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;

using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Module.Common.Models;
using Module.Common.Models.Base;
using Module.Core.BusinessLogic;
using Module.Core.BusinessLogic.CmsContents;
using Module.Core.Common;
using Module.Core.EntitiesInfo;
using Module.Core.LoginSystem.Commons.Framwork;

namespace Web.Cms.MusicManager
{
    public partial class MusicManager : AdminUserControl
    {
        #region Khai báo biến
        private int totalRecords;
        private int page;
        private DateTime dateTo;
        private DateTime dateFrom;
        #endregion

        #region OnInit
        protected override void OnInit(EventArgs e)
        {
            try
            {
                base.OnInit(e);
                CMSZonesBL.GetSub(DropZone, "0", Const.VN, 0, CurrentUser.UserID);
                DropMusician();
                DropSinger();
                DropGroupMusic();
                if (Request.QueryString["zoneId"] != null || Request.QueryString["zoneId"] != "")
                {
                    DropZone.SelectedValue = Request.QueryString["zoneId"];
                }
                if (Request.QueryString["musicianId"] != null || Request.QueryString["musicianId"] != "")
                {
                    dropMusicianId.SelectedValue = Request.QueryString["musicianId"];
                }
                if (Request.QueryString["SingerId"] != null || Request.QueryString["SingerId"] != "")
                {
                    dropSingerId.SelectedValue = Request.QueryString["SingerId"];
                }
                if (Request.QueryString["groupMusicId"] != null || Request.QueryString["groupMusicId"] != "")
                {
                    dropGroupMusicId.SelectedValue = Request.QueryString["groupMusicId"];
                }
                if (Request.QueryString["type"] != null || Request.QueryString["type"] != "")
                {
                    dropType.SelectedValue = Request.QueryString["type"];
                }
                if (Request.QueryString["keyword"] != null || Request.QueryString["keyword"] != "")
                    txtKeysearch.Text = Request.QueryString["keyword"];
                
                if (Request.QueryString["dateFrom"] != null && Request.QueryString["dateFrom"] != "")
                {
                    dateFrom = Convert.ToDateTime(Request.QueryString["dateFrom"].Trim());
                    txtDatefrom.Text = dateFrom.ToString("MM/dd/yyyy");
                }
                else
                {
                    dateFrom = DateTime.Now.AddYears(-2);
                    txtDatefrom.Text = dateFrom.ToString("MM/dd/yyyy");
                }

                if (Request.QueryString["dateTo"] != null && Request.QueryString["dateTo"] != "")
                {
                    dateTo = Convert.ToDateTime(Request.QueryString["dateTo"].Trim());
                    txtDateTo.Text = dateTo.ToString("MM/dd/yyyy");
                }
                else
                {
                    dateTo = DateTime.Now.AddYears(+1);
                    txtDateTo.Text = dateTo.ToString("MM/dd/yyyy");
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Error: " + ex.Message;
            }
        }
        #endregion

        #region OnPreRender
        protected override void OnPreRender(EventArgs e)
        {
            try
            {
                page = int.Parse("0" + Request.QueryString["page"]);
                if (page == 0) page = 1;
                base.OnPreRender(e);
                LoadData();                
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }

        }
        #endregion

        #region LoadData
        private void LoadData()
        {
            if (status == 0)
            {
                status = Convert.ToInt32(Request.QueryString["status"]);
            }
            if (status == 1)
            {
                lbHeader.Text = "DANH SÁCH CÁC BÀI HÁT ĐĂNG TRÊN WEBSITE";
            }
            else if (status == 2)
            {
                lbHeader.Text = "DANH SÁCH CÁC BÀI HÁT CHỜ DUYỆT";
            }
            else if (status == 3)
            {
                lbHeader.Text = "DANH SÁCH CÁC BÀI HÁT NGỪNG ĐĂNG";
            }
            totalRecords = MusicManagerBL.GetCount(txtKeysearch.Text.Trim(), status, CMSZonesBL.GetArrayZoneId(Convert.ToInt32(DropZone.SelectedValue), Const.VN), Convert.ToInt32(dropMusicianId.SelectedValue), Convert.ToInt32(dropSingerId.SelectedValue), dropType.SelectedValue, dateFrom, dateTo.AddDays(+1),"");
            lbTotal.Text ="Tổng số bản ghi: "+ totalRecords.ToString();
            DataSet ds;
            ds = MusicManagerBL.ListMusicManagerPage(txtKeysearch.Text.Trim(), status, CMSZonesBL.GetArrayZoneId(Convert.ToInt32(DropZone.SelectedValue), Const.VN), Convert.ToInt32(dropMusicianId.SelectedValue), Convert.ToInt32(dropSingerId.SelectedValue), dropType.SelectedValue, dateFrom, dateTo.AddDays(+1), "", page, Const.pageSize30, 15, totalRecords, "Default.aspx?ctrlkey=" + CurrentCommand.CtrlKey + "&keyword=" + txtKeysearch.Text.Trim() + "&zoneId=" + DropZone.SelectedValue + "&musicianId=" + dropMusicianId.SelectedValue + "&SingerId=" + dropSingerId.SelectedValue + "&type=" + dropType.SelectedValue + "&dateFrom=" + dateFrom + "&dateTo=" + dateTo + "&page");
            if (ds != null)
            {
                DataTable dtbData = ds.Tables[0];
                DataTable dtbPhanTrang = ds.Tables[1];
                if (dtbData.Rows.Count > 0)
                {
                    grdMusicManager.DataSource = dtbData;
                    grdMusicManager.RowDataBound += new GridViewRowEventHandler(grdMusicManager_RowDataBound);
                    grdMusicManager.DataBind();
                    if (dtbPhanTrang.Rows.Count > 0)
                    {
                        ltlPhanTrang.Text = dtbPhanTrang.Rows[0]["PhanTrang"] + "";
                    }
                }
            }            
        }
        #endregion

        void grdMusicManager_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            ImageButton btnStatus = (ImageButton)e.Row.FindControl("btnStatus");
            Label lbCodId = (Label) e.Row.FindControl("lbCodId");
            DataRowView dataRowView = (DataRowView) e.Row.DataItem;
            Label lbCheckFile = (Label) e.Row.FindControl("lbCheckFile");
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (status == 1)
                {
                    btnStatus.ImageUrl = "/App_Themes/Default/Images/Buttons/btn_pending.gif";
                    btnStatus.OnClientClick = "return confirm('Bạn có chắc chắn gỡ bài hát này xuống không ?')";
                }
                else if (status == 2)
                {
                    btnStatus.ImageUrl = "/App_Themes/Default/Images/Buttons/btn_forward.gif";
                    btnStatus.OnClientClick = "return confirm('Bạn có muốn đăng bài hát này không ?')";
                }
                else if (status == 3)
                {
                    btnStatus.ImageUrl = "/App_Themes/Default/Images/Buttons/btn_forward.gif";
                    btnStatus.OnClientClick = "return confirm('Bạn có muốn khôi phục lại bài hát này không ?')";
                }                
                e.Row.Cells[0].Text = (Const.pageSize30 * (page - 1) + e.Row.DataItemIndex + 1).ToString();
                string codeId = dataRowView["CodeId"].ToString().Trim();
                if (ClsCheckBox.Check(ClsCheckBox.Mobifone, Convert.ToInt32(dataRowView["Type"])) || ClsCheckBox.Check(ClsCheckBox.Viettel, Convert.ToInt32(dataRowView["Type"])) || ClsCheckBox.Check(ClsCheckBox.Vinaphone, Convert.ToInt32(dataRowView["Type"])) || ClsCheckBox.Check(ClsCheckBox.Vietnamobile, Convert.ToInt32(dataRowView["Type"])) || ClsCheckBox.Check(ClsCheckBox.EVNtelecom, Convert.ToInt32(dataRowView["Type"])) || ClsCheckBox.Check(ClsCheckBox.EVNtelecom, Convert.ToInt32(dataRowView["Type"])) || ClsCheckBox.Check(ClsCheckBox.Sfone, Convert.ToInt32(dataRowView["Type"])))
                {
                    lbCodId.Text = dataRowView["CodeId"].ToString();
                }
                else
                {
                    lbCodId.Text = dataRowView["MusicManageId"].ToString();
                }
                //if (codeId =="0")
                //{
                //    lbCodId.Text = dataRowView["MusicManageId"].ToString();
                //}
                //else if (codeId != string.Empty)
                //{
                //    lbCodId.Text = dataRowView["CodeId"].ToString();
                //}
                //else
                //{
                //    lbCodId.Text = dataRowView["MusicManageId"].ToString();
                //}
                if (! File.Exists(Server.MapPath(dataRowView["FileMusic"].ToString())))
                {
                    lbCheckFile.Text = "Lỗi file";
                }
                else
                {
                    lbCheckFile.Text = "OK";
                }
            }
        }


        #region RowCommand
        public void grdMusicManager_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                switch (e.CommandName)
                {
                    case "Commanddelete":
                        try
                        {
                            int musicianId = Convert.ToInt32(e.CommandArgument);
                            MusicManagerBL.Delete(musicianId);                           
                        }
                        catch (Exception ex)
                        {
                            lblMessage.Text = ex.Message;
                        }
                        break;

                    case "CommandStatus":
                        try
                        {
                            int musicianId = Convert.ToInt32(e.CommandArgument);
                            if (status == 2)// chờ duyệt -> xuất bản
                            {
                                MusicManagerBL.UpdateStatus(musicianId, 1);
                            }
                            else if (status == 1)//xuất bản -> gỡ xuống
                            {
                                MusicManagerBL.UpdateStatus(musicianId, 3);
                            }
                            else if (status == 3)//gỡ xuống -> chuyển lên chờ duyệt
                            {
                                MusicManagerBL.UpdateStatus(musicianId, 2);
                            }                            
                        }
                        catch (Exception ex)
                        {
                            lblMessage.Text = ex.Message;
                        }
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }
        #endregion

        #region tìm kiếm
        protected void btnTimKiem_Click(object sender, EventArgs e)
        {
            Response.Redirect("Default.aspx?ctrlkey=" + CurrentCommand.CtrlKey + "&keyword=" + txtKeysearch.Text.Trim() + "&zoneId=" + DropZone.SelectedValue + "&musicianId=" + dropMusicianId.SelectedValue + "&SingerId=" + dropSingerId.SelectedValue + "&type=" + dropType.SelectedValue + "&dateFrom=" + txtDatefrom.Text.Trim() + "&dateTo=" + txtDateTo.Text.Trim() + "&page=" + page);
        }
        #endregion

        #region Load Data DropList
        void DropMusician()
        {
            dropMusicianId.DataBind();
            dropMusicianId.Items.Insert(1, new ListItem("Lựa chọn tên tác giả", "0"));
        }
        void DropSinger()
        {
            CHRTList<SingerInfo> list = SingerBL.SelectAll(Const.show);
            if (list != null && list.Count > 0)
            {
                dropSingerId.DataSource = list;
                dropSingerId.DataTextField = "SingerName";
                dropSingerId.DataValueField = "SingerId";
                dropSingerId.DataBind();
                dropSingerId.Items.Insert(0, new ListItem("Lựa chọn ca sỹ", "0"));
            }
        }
        void DropGroupMusic()
        {
            dropGroupMusicId.DataBind();
            dropGroupMusicId.Items.Insert(0, new ListItem("Lựa chọn nhóm thể hiện", "0"));
        }
        #endregion
        
        private int status;
        public int Status
        {
            set { status = value; }
            get { return status; }
        }
    }
}